<!-- 旋转正方体 魔方 -->
<script>
import * as THREE from 'three';
import { CSS3DRenderer, CSS3DObject } from 'three-css3d';
import imageUrl from '@/assets/images/materials/fu.png'; 

export default {
	name: 'CubeWithDiv',
	mounted() {
		this.initCube();
	},
	methods: {
		initCube() {
			// 获取容器
			const cubecontainer = this.$refs.cubecontainer;

			// 1. 场景、相机和渲染器
			const scene = new THREE.Scene();
			const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000);
			camera.position.set(0, 0, 600);

			// CSS3 渲染器
			const renderer = new CSS3DRenderer();
			renderer.setSize(window.innerWidth, window.innerHeight);
			cubecontainer.appendChild(renderer.domElement);

			// 2. 创建正方体的6个面 (使用 HTML div)
			const cubeSize = 200; // 正方体的尺寸
			const cube = new THREE.Object3D();

			const createFace = (position, rotation) => {
				const element = document.createElement('div');
				element.style.width = `${cubeSize}px`;
				element.style.height = `${cubeSize}px`;
				element.style.backgroundImage = `url(${imageUrl})`;
				element.style.backgroundSize = 'cover';
				element.style.border = '5px solid #ffff92';
				element.style.boxSizing = 'border-box';

				const object = new CSS3DObject(element);
				object.position.set(...position);
				object.rotation.set(...rotation);
				return object;
			};
			
			const faces = [
				// 前面
				createFace([0, 0, cubeSize / 2], [0, 0, 0]),
				// 后面
				createFace([0, 0, -cubeSize / 2], [0, Math.PI, 0]),
				// 左面
				createFace([-cubeSize / 2, 0, 0], [0, -Math.PI / 2, 0]),
				// 右面
				createFace([cubeSize / 2, 0, 0], [0, Math.PI / 2, 0]),
				// 上面
				createFace([0, cubeSize / 2, 0], [-Math.PI / 2, 0, 0]),
				// 下面
				createFace([0, -cubeSize / 2, 0], [Math.PI / 2, 0, 0]),
			];

			faces.forEach((face) => cube.add(face));
			scene.add(cube);

			// 3. 动画
			const animate = () => {
				requestAnimationFrame(animate);
				cube.rotation.x += 0.01; // 旋转角度
				cube.rotation.y += 0.01;
				renderer.render(scene, camera);
			};

			animate();

			// 4. 监听窗口变化，调整尺寸
			window.addEventListener('resize', () => {
				camera.aspect = window.innerWidth / window.innerHeight;
				camera.updateProjectionMatrix();
				renderer.setSize(window.innerWidth, window.innerHeight);
			});
		},
	},
};
</script>

<template>
	<div ref="cubecontainer" class="cube-container"></div>
</template>

<style lang="scss" scoped>
.cube-container {
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	position: relative;
}
</style>
